package com.icesoft.core.web.suppose.mapping;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@AllArgsConstructor
@Slf4j
public class ConditonMappingCondition implements RequestCondition<ConditonMappingCondition> {
	@Getter
	private List<HeaderMapping> headerMappings;
	@Getter
	private VersionCodeMapping versionCode;

	@Override
	public ConditonMappingCondition combine(ConditonMappingCondition other) {
		return new ConditonMappingCondition(other.headerMappings, other.versionCode);
	}

	@Override
	public ConditonMappingCondition getMatchingCondition(HttpServletRequest request) {
		boolean headerMappingMatch = true;
		if (headerMappings != null) {
			headerMappingMatch = false;
			for (HeaderMapping headerMapping : headerMappings) {
				String value = request.getHeader(headerMapping.name());
				log.trace("{}={}", headerMapping.name(), value);
				if (StringUtils.equals(value, headerMapping.value())) {
					headerMappingMatch = true;
					break;
				}
			}

		}
		boolean versionCodeMatch = true;
		if (versionCode != null) {
			versionCodeMatch = false;
			String value = request.getHeader(versionCode.name());
			log.trace("{}={}", versionCode.name(), value);
			if (StringUtils.isNumeric(value) && Integer.parseInt(value) >= versionCode.min()) {
				versionCodeMatch = true;
			}
		}
		if (headerMappingMatch && versionCodeMatch) {
			log.trace("versionCode mapping Match");
			return this;
		}
		return null;
	}

	// 对两个RequestCondition对象进行比较，这里主要是如果存在两个注册的一样的Mapping，那么就会对
	// 这两个Mapping进行排序，以判断哪个Mapping更适合处理当前request请求
	@Override
	public int compareTo(ConditonMappingCondition other, HttpServletRequest request) {
		if (versionCode != null && other.versionCode != null) {
			return other.versionCode.min() - versionCode.min();
		}
		return 0;
	}

}
